import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
    baseURL: 'http://localhost:5050',  // FastAPI 后端地址
    timeout: 5000,
    withCredentials: true
})

// 请求拦截器
api.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        if (token) {
            // 设置请求头
            config.headers.token = `${token}`
        }
        return config
    },
    error => {

        return Promise.reject(error)
    }
)

// 响应拦截器
api.interceptors.response.use(
    response => response,
    error => {
        const errorMessage = error.response?.data?.detail || '网络错误，请稍后重试'

        if (error.response?.status === 401) {
            // 清除token
            localStorage.removeItem('token')
            // 重定向到登录页面
            if (window.location.pathname !== '/') {
                window.location.href = '/'
            }
        }

        error.message = errorMessage
        return Promise.reject(error)
    }
)

export default api